package com.gupao.dubbo.netty.server;

import com.gupao.dubbo.netty.RpcRquest;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;

import java.lang.reflect.Method;
import java.util.Map;

public class RpcHandler extends ChannelInboundHandlerAdapter {
    public RpcHandler(Map<String, Object> handlerMap) {
        this.handlerMap = handlerMap;
    }

    Map<String, Object> handlerMap;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRquest req = (RpcRquest) msg;
        Object o = handlerMap.get(req.getClassName());
        if (o == null) {
            System.err.println("can not find handler for class:" + req.getClassName());
            ctx.writeAndFlush("error");
            return;
        }
        Method method = o.getClass().getMethod(req.getMethodName(), req.getParameterTypes());
        Object response = method.invoke(o, req.getArgs());
        ctx.writeAndFlush(response);
    }
}
